package com.zhengke.controller;

import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.object.MyAjaxResult;
import com.zhengke.common.object.ZTreeNode;
import com.zhengke.common.util.*;
import com.zhengke.pojo.MallGoodsClass;
import com.zhengke.service.GoodsClassService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * *******************************
 * 项目名称：tvmall-parent
 * 文件名称：FileController
 * 类说明：  测试fastdfs图片上传
 * 创建时间：2020/2/11 15:17
 *
 * @author 王鑫
 * @version 1.0
 * *******************************
 */
@Controller
@RequestMapping("fastDFS02")
public class FileController02 {

    @Autowired
    private GoodsClassService service;

    /**
     * 到商品分类页面
     *
     * @return
     */
    @RequestMapping("toMgr.do")
    public String query() {
        return "fdfsUpload/testPage02";
    }

    /**
     * 商品分类树
     *
     * @param id 返回数据字典的Json格式数据
     */
    @ResponseBody
    @RequestMapping("tree.do")
    public List<ZTreeNode> tree(String id) {
        List<ZTreeNode> list = new ArrayList<ZTreeNode>();
        if (id != null) {
            list = service.queryParent(id);
            return list;
        }
        list = service.queryParent("0");
        return list;
    }

    /**
     * @return 到修改商品分类页面
     */
    @RequestMapping("toGcUpd.do")
    public String toUpdGoodsClass(String gcId, HttpServletRequest request, ModelMap model) {
        try {
            MallGoodsClass mgc = service.queryById(Integer.parseInt(gcId));
            //model.addAttribute(mgc);
            model.addAttribute("mgc", mgc);

            String picPath = mgc.getGcPicpath();
            if (picPath == null || "".equals(picPath))
                model.put("gcPicPath", request.getSession().getServletContext().getRealPath("/images/") + "/noPic.png");
            else
                model.put("gcPicPath", mgc.getGcPicpath());

            String imgW = LoadProperties.findValue("imgW");
            String imgH = LoadProperties.findValue("imgH");
            model.put("imgW", imgW);
            model.put("imgH", imgH);
            //读取config.properties查找访问路径的ip+端口
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            model.put("fileServerUrl", fileServerUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fdfsUpload/fdfsUpload02";
    }

    /**
     * 删除商品分类信息
     *
     * @param gcId
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteClass.do")
    public AjaxDone deleteGcClass(String gcId) {
        try {
            int rst = service.deleteById(Integer.parseInt(gcId));
            if (rst == -1) {
                return new AjaxDone("300", "该商品分类有子分类,请先删除其子分类!");
            }
            if (rst >= 0) {
                return new AjaxDone("200", "删除成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 上传原始图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadImage.do")
    public AjaxDone updateImage(@RequestParam("image") CommonsMultipartFile image) {
        try {
            String imageFileName = image.getOriginalFilename();

            if (imageFileName.indexOf(".jpg") == -1
                    && imageFileName.indexOf(".gif") == -1
                    && imageFileName.indexOf(".png") == -1
                    && imageFileName.indexOf(".jpeg") == -1) {
                return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }

            String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            if (image != null && !image.isEmpty()) {
                String path = LoadProperties.findValue("imgPath") + "/" + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileUtils.copyInputStreamToFile(image.getInputStream(), file);
                String rtnPath = LoadProperties.findValue("viewUrl") + "?path=" + file.getPath();

                return new AjaxDone("200", "上传成功", rtnPath, path);
            } else {
                return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "上传失败");
    }

    /**
     * 上传剪切后的图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadCanvas.do")
    public AjaxDone updateConvars(String gcId, String canvasData, String delFile) {
        try {
            String path = LoadProperties.findValue("imgPath") + "/";
            String fileName = DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + ".jpg";

            File file = Base64ToImage.decodeBase64ToImage(canvasData, path, fileName);

            //删除原图片
            File delete = new File(delFile);
            if (delete != null) {
                delete.delete();
            }

            if (file != null) {
                String imgW = LoadProperties.findValue("imgW");
                String imgH = LoadProperties.findValue("imgH");
                //保存canvas转成的缩略图
                String filePath = ImageUtil.thumbnailImage(file.getPath(), Integer.parseInt(imgW), Integer.parseInt(imgH), true);
                //删除canvas原图
                file.delete();

                /*
                fastDFS操作
                 */
                //获取文件的扩展名
                String filename = fileName;
                //获取文件后缀名 从最后一个点后一位截取
                String extName = fileName.substring(filename.lastIndexOf(".") + 1);
                //上传fastDFS后图片完整地址
                String file_id = FastDfsApiOpr.upload(filePath, extName);
                //读取config.properties查找访问路径的ip+端口
                String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
                String rtPath = fileServerUrl + file_id;
                System.out.println(file_id);
                System.out.println(fileServerUrl);
                //删除剪切后的本地图片
                File delCanvas = new File(filePath);
                if (delCanvas != null) {
                    delCanvas.delete();
                }

                return new AjaxDone("200", "上传成功!", rtPath, file_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 保存商品分类信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("updateGoodsClass.do")
    public AjaxDone saveGoodsClass(Integer gcId, String gcName, Short gcSort, String gcDescription, String gcPicpath, String fileId) {
        try {
            MallGoodsClass mgc = new MallGoodsClass();
            mgc.setGcId(gcId);
            mgc.setGcName(gcName);
            mgc.setGcSort(gcSort);
            mgc.setGcDescription(gcDescription);
            mgc.setGcPicpath(gcPicpath);

            /**
             * 删除已经之前上传到服务器的图片，节省存储资源
             */
            //先判断fdfs图片服务器上原图片是否存在
            boolean isExist = false;
            String urlStr = LoadProperties.findValue("FILE_SERVER_URL") + fileId;
            try {
                URL url = new URL(urlStr);// 注：urlStr中需将空格替换为%20,否则报505
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                int state = conn.getResponseCode();
                if (state == 200) {
                    isExist = true;
                } else {
                    isExist = false;
                }
            } catch (Exception e) {
                isExist = false;
            }
            //排除修改为fdfs上传之前路径问题
            int index = fileId.indexOf("/");
            if (fileId != null && index >= 0 && isExist == true) {
                // eg:    /group1/M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                fileId = fileId.substring(1);//   group1/M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                String groupName = fileId.substring(0, fileId.indexOf("/"));//group01
                String fileName = fileId.substring(fileId.indexOf("/") + 1);///M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                FastDfsApiOpr.delete(groupName, fileName);
            }

            /*
            保存修改信息
             */
            int rst = service.update(mgc);
            if (rst > 0) {
                Map<String, String> rtnMap = new HashMap<String, String>();
                rtnMap.put("gcName", mgc.getGcName());
                return new AjaxDone("200", "保存成功!", "", rtnMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }


    /**
     * 直接上传原图  MultipartFile 是SpringMVC封装好的API方便操作上传的文件的
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping("fdfsUpload.do")
    public AjaxDone upload(MultipartFile file) {
        try {
            //获取文件的扩展名
            String filename = file.getOriginalFilename();
            //获取文件后缀名 从最后一个点后一位截取
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //图片完整地址
            String file_id = FastDfsApiOpr.upload(file.getBytes(), extName);
            //读取config.properties查找访问路径的ip+端口
            String rtnPath = LoadProperties.findValue("FILE_SERVER_URL");
            System.out.println(file_id);
            System.out.println(rtnPath);
            return new AjaxDone("200", "上传成功!", file_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxDone("300", "上传失败!" + e.getMessage());
        }
    }
}
